package cn.sh.yhk.controller;

import cn.sh.yhk.base.vo.BaseResponse;
import cn.sh.yhk.model.po.CategoryPo;
import cn.sh.yhk.model.po.MaitaiInfoPo;
import cn.sh.yhk.model.vo.CategoryVo;
import cn.sh.yhk.model.vo.MaitaiInfoVo;
import cn.sh.yhk.service.CategoryService;
import cn.sh.yhk.service.MaotaiInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/maotai")
public class MaotaiController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    MaotaiInfoService maotaiInfoService;

    @PostMapping("/getcategory")
    public BaseResponse<List<CategoryVo>> downloadimg() {
        List<CategoryPo> list = categoryService.list();
        List<CategoryVo> resultList = list.stream().map(po -> {
            CategoryVo vo = new CategoryVo();
            BeanUtils.copyProperties(po, vo);
            return vo;
        }).collect(Collectors.toList());
        return BaseResponse.success(resultList);
    }


    @PostMapping("/save")
    public BaseResponse<MaitaiInfoVo> saveInfo(@RequestBody MaitaiInfoVo vo) {
        MaitaiInfoPo po = new MaitaiInfoPo();
        QueryWrapper<MaitaiInfoPo> queryWrapper = new QueryWrapper<>(po);
        queryWrapper.eq("qrcode", vo.getQrcode());

        if (maotaiInfoService.count(queryWrapper) > 1) {
            return BaseResponse.fail("号码已存在");
        } else {
            BeanUtils.copyProperties(vo, po);
            po.setImages(Arrays.toString(vo.getImages()));
            maotaiInfoService.save(po);
            return BaseResponse.success(vo);
        }


    }


    @PostMapping("/list")
    public BaseResponse<Page<MaitaiInfoVo>> list(@RequestBody MaitaiInfoVo vo) {
        MaitaiInfoPo po = new MaitaiInfoPo();
        po.setQrcode(vo.getQrcode());
        Page<MaitaiInfoPo> pageList = maotaiInfoService.getMaotaiInfoPage(vo.getPage(), vo.getPageSize(), po);
        Page<MaitaiInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(pageList, pageVo);
        return BaseResponse.success(pageVo);
    }

}
